package com.hww.web;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


/**
 * @Author: youdao.hww
 * @Date: 10/30/24
 * @Desc:
 */
@Slf4j
@RestController
public class RedisController {

    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping("/lock")
    public void doSomething() {
        // 使用RedissonClient进行操作，例如获取一个分布式锁
        RLock lock = redissonClient.getLock("doSomethingLock");
        try {
            //waitTime: 获取锁的最大等待时间。如果在指定时间内无法获取锁，方法将返回 false
            //leaseTime: 锁将在指定的租约时间后自动释放
            //TimeUnit:  时间单位，用于指定 waitTime 和 leaseTime 的时间单位
            boolean isLocked = lock.tryLock(5, 10, TimeUnit.SECONDS);
            if (isLocked) {
                log.info("{},加锁成功", Thread.currentThread().getId());
                // 执行需要加锁的代码块
                Thread.sleep(8000);
                log.info("{},执行业务逻辑成功", Thread.currentThread().getId());
            } else {
                log.info("{},暂未获取到锁", Thread.currentThread().getId());
            }
        } catch (InterruptedException e) {
            // 处理中断异常
        } finally {
            if (lock.isHeldByCurrentThread()) {
                log.info("{},释放成功", Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }
}
